<template>
  <div class="alarm-container">
    <div class="content">
      <div class="search">
        <cq-region v-model="state.queryParams.regionCode"></cq-region>
        <van-dropdown-menu
          ref="menuRef"
          :close-on-click-overlay="false"
          :close-on-click-outside="false"
        >
          <van-dropdown-item ref="itemRef">
            <template #title>
              <span class="filter-o"><van-icon name="filter-o" size="20" /></span>
            </template>

            <div class="filter-content">
              <van-form ref="formRef">
                <van-cell-group>
                  <van-field
                    v-model="state.formData.rainfallCycleName"
                    label="降雨轮次"
                    @click="querySelect('rainfallCycle')"
                    placeholder="请选择降雨轮次"
                    readonly
                    label-align="top"
                    right-icon="arrow-down"
                    style="width: 50%"
                    v-if="state.queryParams.isDq == '2'"
                  />
                  <van-field
                    v-model="state.formData.levelName"
                    label="预警等级"
                    @click="querySelect('warningLevel')"
                    placeholder="请选择降雨轮次"
                    readonly
                    label-align="top"
                    right-icon="arrow-down"
                    style="width: 50%"
                  />
                  <van-field
                    v-model="state.formData.isDrillName"
                    name="region"
                    label="是否演练"
                    @click="querySelect('isDrill')"
                    style="width: 50%"
                    readonly
                    label-align="top"
                    right-icon="arrow-down"
                    placeholder="请选择是否演练"
                  />
                  <van-field
                    v-model="state.formData.haveWorkName"
                    name="region"
                    label="响应状态"
                    @click="querySelect('haveWork')"
                    style="width: 50%"
                    readonly
                    label-align="top"
                    right-icon="arrow-down"
                    placeholder="请选择响应状态"
                    v-if="state.queryParams.isDq == '2'"
                  />
                  <van-field
                    v-model="state.formData.warningBasisName"
                    name="region"
                    label="预警来源"
                    @click="querySelect('source')"
                    style="width: 50%"
                    readonly
                    label-align="top"
                    right-icon="arrow-down"
                    placeholder="请选择预警来源"
                    v-if="state.queryParams.isDq == '2'"
                  />
                  <van-field
                    v-model="state.formData.warningTypeName"
                    label="预警类型"
                    @click="querySelect('type')"
                    style="width: 50%"
                    readonly
                    label-align="top"
                    right-icon="arrow-down"
                    placeholder="请选择预警类型"
                    v-if="state.queryParams.isDq == '2'"
                  />

                  <van-field
                    v-model="state.queryParams.riskPoint"
                    label="预警点位名称"
                    label-align="top"
                    placeholder="请输入预警点位名称"
                    v-if="state.queryParams.isDq == '1'"
                  />

                  <van-field
                    v-model="state.queryParams.eventNum"
                    label="预警编码"
                    label-align="top"
                    placeholder="请输入预警编码"
                    v-if="state.queryParams.isDq == '1'"
                  />
                </van-cell-group>
              </van-form>
            </div>

            <div style="padding: 5px 10px">
              <van-button type="primary" block @click="onFirm">确认</van-button>
              <van-button style="margin-top: 5px" block @click="onReset">重置</van-button>
            </div>
          </van-dropdown-item>
        </van-dropdown-menu>
      </div>
    </div>
    <div class="button-group">
      <van-button
        round
        :type="state.active == item.name ? 'primary' : 'default'"
        v-for="(item, index) in state.buttonGroup"
        :key="index"
        @click="handleChange(item.name)"
        style="margin-right: 12px"
        >{{ item.name }}</van-button
      >
    </div>

    <div class="alarm-list" ref="listContainer">
      <van-pull-refresh v-model="refreshing" @refresh="onLoad('refresh')">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div
            class="alarm-item"
            v-for="(item, index) in state.alarmList"
            :key="index"
            @click="goDetails(item)"
          >
            <div class="alarm-header">
              <van-image width="24" height="24" fit="cover" round :src="locationIcon" />
              <span class="t1">{{ item.districtName }}</span>
              <span class="t2">{{ item.rainfallCycle }}</span>
              <span
                class="t3"
                :style="{
                  color: getColor(item.warningLevel),
                  borderColor: getColor(item.warningLevel),
                }"
                >{{ MAP_STATE.warningLevel[item.warningLevel] }}</span
              >
            </div>
            <div class="alarm-content">
              <div class="c1">
                {{ item.warningName }}
              </div>
              <div class="c2">
                {{ item.warningContent }}
              </div>
              <div class="line"></div>

              <div class="status" v-if="state.queryParams.isDq == '2'">
                <div>
                  预警状态
                  <span :style="{ color: item.warningStatus == 1 ? '#007FFF' : '' }">{{
                    MAP_STATE.warningStatus[item.warningStatus]
                  }}</span>
                </div>
                <div>
                  响应状态
                  <span :style="{ color: item.ifResponse == 0 ? '' : '#007FFF' }">{{
                    MAP_STATE.ifResponse[item.ifResponse]
                  }}</span>
                </div>
                <div>
                  叫应状态
                  <span :style="{ color: item.callingState == 1 ? '' : '#007FFF' }">{{
                    MAP_STATE.callingState[item.callingState]
                  }}</span>
                </div>
                <div>
                  是否演练 <span>{{ MAP_STATE.isDrill[item.isDrill] }}</span>
                </div>
                <div>
                  {{ formattedDate(item.warningPeriodStart) }} -
                  {{ formattedDate(item.warningPeriodEnd) }}
                </div>
              </div>

              <div class="status point" v-else>
                <div>
                  降水量 <span>{{ item.nextPrecipitation }}毫米</span>
                </div>
                <div>
                  预警阈值 <span>{{ item.warningThreshold }}毫米</span>
                </div>
                <div>
                  响应状态
                  <span :style="{ color: item.ifResponse == 0 ? '' : '#007FFF' }">{{
                    MAP_STATE.ifResponse[item.ifResponse]
                  }}</span>
                </div>
                <div>
                  是否演练 <span>{{ MAP_STATE.isDrill[item.isDrill] }}</span>
                </div>
                <div>
                  {{ formattedDate(item.warningPeriodStart) }} -
                  {{ formattedDate(item.warningPeriodEnd) }}
                </div>
              </div>

              <div class="confirm">
                <van-button type="primary" block @click.stop="createOrder(item)"
                  >创建工单</van-button
                >
              </div>
            </div>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>

    <!-- <van-overlay :show="state.show" style="z-index: 2000">
      <div class="wrapper">
        <div class="block">
          <div class="title">叫应后会生成响应任务请及时处理</div>
          <div class="buttons">
            <van-button
              style="background-color: #e6f7ff; color: #1890ff; width: 50%"
              @click="state.show = false"
              >取消</van-button
            >
            <van-button type="primary" style="width: 50%" @click="handleConfirm"
              >确认叫应</van-button
            >
          </div>
        </div>
      </div>
    </van-overlay> -->

    <van-popup v-model:show="state.showPicker" destroy-on-close position="bottom">
      <van-picker
        :columns="state.columns"
        :model-value="state.pickerValue"
        @confirm="onPicker"
        @cancel="state.showPicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import locationIcon from "@/assets/images/task/icon_region_location.png";
import { useRouter } from "vue-router";
import { getResponesTaskListApi, getSelectRainfallCycle } from "@/api/eventTask";
import moment from "moment";
import CqRegion from "@/components/CqRegion.vue";
import { getDictDataApi } from "@/api/common";
const router = useRouter();
const state = reactive({
  active: "区域响应",
  buttonGroup: [
    {
      name: "区域响应",
    },
    {
      name: "点位响应",
    },
  ],
  alarmList: [],
  formData: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    isDq: 2, // 1.点位预警 2.区域预警
  },
  pages: 0,
  showPicker: false,
  columns: [],
});
// 分页参数
const refreshing = ref(false);
const loading = ref(false);
const finished = ref(false);

const listContainer = ref(null);
// 点击预警按钮
const handleChange = (val) => {
  state.active = val;
  // state.queryParams.pageNum = 1;
  state.queryParams = {
    pageNum: 1,
    pageSize: 10,
    isDq: state.active == "区域响应" ? 2 : 1,
  };
  getResponesTaskListFn();
  state.pickerValue = [];
  state.pickerType = "";
  state.columns = [];
  state.formData = {};
  // if (val == "区域响应") {
  //   state.queryParams.isDq = 2;
  //   getResponesTaskListFn();
  // } else {
  //   state.queryParams.isDq = 1;
  //   getResponesTaskListFn();
  // }

  // 滚动到顶部
  listContainer.value.scrollTop = 0;
};

// 创建工单
const createOrder = (item) => {
  router.push({
    path: "/responesTaskCreateOrder",
    query: {
      code: item.regionCode,
      riskPointId: item.riskPointId,
      riskPointName: item.riskPoint,
      taskId: item.id,
      type: state.active,
      warningContent: item.warningContent,
    },
  });
};
// 点击确认呼应
const handleConfirm = () => {
  state.show = false;
};
// 获取响应列表
const getResponesTaskListFn = () => {
  getResponesTaskListApi(state.queryParams)
    .then(({ data }) => {
      if (data && data.code == 200) {
        state.pages = Math.ceil(data.total / state.queryParams.pageSize);

        let list = data.rows || [];

        if (state.queryParams.pageNum == 1) {
          state.alarmList = list;
        } else {
          state.alarmList = state.alarmList.concat(list);
        }
        if (state.queryParams.pageNum == state.pages || state.pages == 0) {
          finished.value = true;
        }
      } else {
        finished.value = true;
      }
    })
    .catch((err) => {
      finished.value = true;
    })
    .finally(() => {
      loading.value = false;
    });
};

const onLoad = (type) => {
  if (type === "refresh") {
    finished.value = false;
    loading.value = true;
  }

  if (refreshing.value || type === "refresh") {
    state.pages = 0;
    state.queryParams.pageNum = 1;
    state.alarmList = [];
    refreshing.value = false;
  }

  if (type !== "refresh") {
    if (state.queryParams.pageNum >= state.pages) return;
    state.queryParams.pageNum++;
  }
  getResponesTaskListFn();
};

// 状态映射
const MAP_STATE = {
  // 风险等级
  warningLevel: {
    3: "低风险",
    2: "中风险",
    1: "高风险",
  },
  // 预警状态
  warningStatus: {
    1: "生效中",
    2: "已结束",
  },
  // 响应状态
  ifResponse: {
    0: "未响应",
    1: "已响应",
    2: "已结束",
  },
  // 叫应状态
  callingState: {
    1: "未叫应",
    2: "已叫应",
    3: "已结束",
  },
  // 是否演练
  isDrill: {
    0: "否",
    1: "是",
  },
};

// 根据状态返回颜色
const getColor = (key) => {
  switch (key) {
    case 3:
      return "#00b042";
    case 2:
      return "#FC9C00";
    case 1:
      return "#FF4D4F";
    default:
      break;
  }
};

// 时间格式化
const formattedDate = (date) => {
  return moment(date).format("MM/DD HH:mm");
};

// 跳转详情
const goDetails = (item) => {
  router.push({
    path: "/responseTaskDetail",
    query: {
      id: item.id,
    },
  });
};

// 降雨轮次下拉
const rainfallCycleOptions = ref([]);
// 预警等级下拉
const warningLevelOptions = ref([]);
// 响应状态下拉
const haveWorkOptions = [
  {
    text: "未响应",
    value: "0",
  },
  {
    text: "已响应",
    value: "1",
  },
  {
    text: "已完成",
    value: "2",
  },
];
// 预警来源下拉
const sourceOptions = ref([
  { text: "重要气象专报", value: "重要气象专报" },
  { text: "每日气象要讯", value: "每日气象要讯" },
  { text: "6小时暴雨预警", value: "6小时暴雨预警" },
  { text: "区域手动预警", value: "区域手动预警" },
]);

// 预警类型下拉
const typeOptions = ref([
  { text: "区域气象自动预警", value: "区域气象自动预警" },
  { text: "区域手动预警", value: "区域手动预警" },
]);

// 是否演练
const isDrillOptions = [
  {
    text: "否",
    value: "0",
  },
  {
    text: "是",
    value: "1",
  },
];
// 点击查询条件
const querySelect = (type) => {
  if (type === "haveWork") {
    state.columns = haveWorkOptions;
  } else if (type === "warningLevel") {
    state.columns = warningLevelOptions.value;
  } else if (type === "type") {
    state.columns = typeOptions;
  } else if (type === "source") {
    state.columns = sourceOptions;
  } else if (type === "rainfallCycle") {
    state.columns = rainfallCycleOptions.value;
  } else if (type === "isDrill") {
    state.columns = isDrillOptions;
  }
  state.showPicker = true;
  state.pickerType = type;
};

// 选择下拉弹窗
const onPicker = ({ selectedValues, selectedOptions }) => {
  switch (state.pickerType) {
    case "haveWork":
      state.queryParams.haveWork = selectedOptions[0].value;
      state.formData.haveWorkName = selectedOptions[0].text;
      break;
    case "isDrill":
      // state.formData.isDrill = selectedValues[0].value;
      state.queryParams.isDrill = selectedOptions[0].value;
      state.formData.isDrillName = selectedOptions[0].text;
      break;
    case "type":
      // state.formData.workType = selectedValues[0].value;
      state.queryParams.warningType = selectedOptions[0].value;
      state.formData.warningTypeName = selectedOptions[0].text;
      break;
    case "source":
      // state.formData.rainfallCycle = selectedValues[0].value;
      state.queryParams.warningBasis = selectedOptions[0].value;
      state.formData.warningBasisName = selectedOptions[0].text;
      break;
    case "rainfallCycle":
      state.queryParams.rainfallCycle = selectedOptions[0].value;
      state.formData.rainfallCycleName = selectedOptions[0].text;
      break;
    case "warningLevel":
      state.queryParams.level = selectedOptions[0].value;
      state.formData.levelName = selectedOptions[0].text;
      break;
    default:
      break;
  }
  //分类型选择器确定
  state.pickerValue = selectedValues;
  state.showPicker = false;
};

// 获取降雨轮次列表
const geRainfallCycleList = async () => {
  let { data } = await getSelectRainfallCycle();
  if (data && data.code == 200) {
    rainfallCycleOptions.value =
      data.data.map((item) => ({
        text: item, // 或者字段名取决于接口返回结构
        value: item,
      })) || [];
  }
};

// 获取预警等级
const getWarningLevelOptions = async () => {
  const { data } = await getDictDataApi("sys_warn_level");
  if (data && data.code == 200) {
    warningLevelOptions.value =
      data.data.map((item) => ({
        ...item,
        text: item.dictlabel, // 或者字段名取决于接口返回结构
        value: item.dictvalue,
      })) || [];
  }
};

const menuRef = ref(null);
// 确认
const onFirm = () => {
  state.queryParams.pageNum = 1;
  getResponesTaskListFn();
  menuRef.value.close();
};

// 重置
const onReset = () => {
  state.queryParams = {
    pageNum: 1,
    pageSize: 10,
    isDq: state.active == "区域响应" ? 2 : 1,
  };
  state.pickerValue = [];
  state.pickerType = "";
  state.columns = [];
  state.formData = {};
  getResponesTaskListFn();
  menuRef.value.close();
};

onMounted(() => {
  geRainfallCycleList();
  getWarningLevelOptions();
  getResponesTaskListFn();
});
</script>

<style lang="less" scoped>
.alarm-container {
  height: 100%;
  .content {
    background: rgba(243, 243, 243, 1);
    margin-bottom: 10px;
    .search {
      height: 30px;
      display: flex;
      justify-content: space-between;
      .van-field {
        width: calc(100% - 40px);
        background: #fff;
        height: 100%;
        display: flex;
        align-items: center;
        padding: 0 10px;
        margin-bottom: 10px;
      }
      :deep(.van-dropdown-menu__bar) {
        background: #fff;
        margin-left: 10px;
        height: 30px;
        width: 30px;
        .van-dropdown-menu__title {
          padding: 0;
        }
        .van-dropdown-menu__title:after {
          display: none;
        }
        .van-dropdown-menu__title--down:after {
          display: none;
        }
      }
      :deep(.van-dropdown-item) {
        top: 150px !important;
      }
      .filter-o {
        height: 30px;
        width: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .filter-content {
        padding: 10px 0;
        width: 100%;
        .van-form {
          display: flex;
          flex-wrap: wrap;
        }
        :deep(.van-cell-group) {
          display: flex;
          flex-wrap: wrap;
        }
        :deep(.van-field) {
          width: 100%;
          height: auto;
          .van-field__value {
            background: #f2f2f2;
            height: 40px;
            display: flex;
            align-items: center;
            padding: 0 10px;
            .van-field__body {
              width: 100%;
            }
          }
        }
      }
    }
  }

  .alarm-list {
    margin-top: 12px;
    // height: calc(100%);
    height: 100%;
    overflow-y: auto;
    .alarm-item {
      background: #ffffff;
      border-radius: 8px 8px 8px 8px;
      margin-bottom: 12px;
      .alarm-header {
        height: 36px;
        width: 100%;
        background: linear-gradient(
          90deg,
          rgba(0, 127, 255, 0.08) 0%,
          rgba(0, 127, 255, 0) 100%
        );
        display: flex;
        padding-top: 8px;
        padding-left: 12px;
        padding-right: 12px;
        box-sizing: border-box;
        span {
          margin-top: 2px;
        }
        font-family: PingFang TC, PingFang TC;

        .t1 {
          font-weight: 600;
          font-size: 12px;
          color: rgba(0, 0, 0, 0.9);
          margin-left: 4px;
        }

        .t2 {
          font-weight: 400;
          font-size: 12px;
          color: rgba(0, 0, 0, 0.6);
          margin-left: 12px;
        }

        .t3 {
          border-radius: 4px 4px 4px 4px;
          border: 1px solid #00b042;
          color: #00b042;
          text-align: center;
          padding: 0 4px;
          height: 18px;
          margin-left: auto;
        }
      }

      .alarm-content {
        padding: 8px 12px 12px 12px;
        font-family: PingFang TC, PingFang TC;
        .c1 {
          font-weight: 600;
          font-size: 16px;
          color: rgba(0, 0, 0, 0.9);
        }

        .c2 {
          font-weight: 400;
          font-size: 14px;
          color: rgba(0, 0, 0, 0.6);
          margin-top: 4px;
        }

        .line {
          border: 1px solid #e7e7e7;
          margin: 8px 0;
        }

        .status {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 8px 18px;
          font-family: PingFang TC, PingFang TC;
          font-weight: 400;
          font-size: 12px;
          color: rgba(0, 0, 0, 0.4);
          div:nth-child(1) {
            span {
              color: rgba(0, 0, 0, 0.9);
            }
          }
          div {
            span {
              color: rgba(245, 34, 45, 1);
            }
          }
          div:last-child {
            grid-column: span 2; // 可调整为 span 2 或 span 3 来占用更多列
            width: 100%; // 根据需要可选
            text-align: right;
          }
        }

        .status.point {
          grid-template-columns: 100px 110px 100px;
          gap: 8px;
          div:nth-child(2) {
            span {
              color: rgba(0, 127, 255, 1);
            }
          }
          div {
            span {
              color: rgba(245, 34, 45, 1);
            }
          }
        }

        .confirm {
          width: 100%;
          margin-top: 8px;
        }
      }
    }
  }
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;

  .block {
    width: 300px;
    // height: 160px;
    background: #ffffff;
    border-radius: 12px 12px 12px 12px;
    padding: 24px;
    box-sizing: border-box;
    text-align: center;
    .title {
      font-family: PingFang TC, PingFang TC;
      font-weight: 600;
      font-size: 18px;
      color: rgba(0, 0, 0, 0.9);
    }

    .buttons {
      margin-top: 24px;
      display: flex;
      gap: 12px;
    }
  }
}
</style>
